package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.Destination;
import cn.wolfcode.wolf2w.business.api.domain.Region;
import cn.wolfcode.wolf2w.business.mapper.DestinationMapper;
import cn.wolfcode.wolf2w.business.mapper.RegionMapper;
import cn.wolfcode.wolf2w.business.query.DestinationQuery;
import cn.wolfcode.wolf2w.business.service.IDestinationService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 目的地Service业务层处理
 *
 * @author ysc
 * @date 2024-12-17
 */
@Service
@Transactional
public class DestinationServiceImpl extends ServiceImpl<DestinationMapper, Destination> implements IDestinationService {

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public IPage<Destination> queryPage(DestinationQuery qo) {
        IPage<Destination> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        return lambdaQuery()
                .page(page);
    }

    @Override
    public List<Destination> queryDestinationByRegionId(Long regionId) {
        List<Destination> list = null;
        if (regionId == -1) {
            //国内
            list = lambdaQuery().eq(Destination::getParentId, 1).list();

        } else {
            Region region = regionMapper.selectById(regionId);
            String refIds = region.getRefIds();
            String[] split = refIds.split(",");
            list = new ArrayList<>();
            for (String s : split) {
                Long destId = Long.valueOf(s);
                Destination destination = baseMapper.selectById(destId);
                list.add(destination);
            }
        }
        for (Destination destination : list) {
            Long id = destination.getId();
            List<Destination> children = lambdaQuery().eq(Destination::getParentId, id)
                    .last("limit 10")
                    .list();
            destination.setChildren(children);
        }

        return list;
    }

    @Override
    public List<Destination> queryToastsByReDestId(Long destId) {
        List<Destination> list = new ArrayList<>();
        craeteToasts(list, destId);
//        Collections.reverse(list); //反序
        return list;
    }

    //递归
    private void craeteToasts(List<Destination> list, Long destId) {
        if (destId == null) {
            return;
        }
        Destination destination = baseMapper.selectById(destId);
        craeteToasts(list, destination.getParentId());
        list.add(destination);
    }
}
